package com.hk.springsecurity04.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hk.springsecurity04.entity.UserEntity;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author by 何坤
 * @Classname CustomAuthenticationFilter
 * @Description TODO
 * @Date 2019/12/23 17:08
 */
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE) ||
            request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)){
            ObjectMapper objectMapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = null;
            try(InputStream is = request.getInputStream()) {
                UserEntity userEntity = objectMapper.readValue(is, UserEntity.class);
                usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userEntity.getPhone(), userEntity.getPassword());
            } catch (IOException e) {
                e.printStackTrace();
                usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        "", "");
            } finally {
                setDetails(request, usernamePasswordAuthenticationToken);
                return this.getAuthenticationManager().authenticate(usernamePasswordAuthenticationToken);
            }
        } else {
            return super.attemptAuthentication(request, response);
        }
    }
}
